import { Component, EventEmitter, HostBinding, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { FormExpressionConfig, DomService, FormBasicService } from '@farris/designer-services';
// import { ExpressioneditorComponent, Schema as ExpSchema } from '@gsp-svc/expression';
// import { FilterExprService } from './filter-expr.service';

/**
 * 表达式编辑器
 */
@Component({
    selector: 'app-expression-editor',
    templateUrl: './expression-editor.component.html',
    // providers: [FilterExprService]
})
export class ExpressionEditorComponent implements OnInit {
    /**
     * 关闭按钮事件
     */
    @Output() closeModal = new EventEmitter<any>();
    /**
     * 确定按钮事件
     */
    @Output() submitModal = new EventEmitter<any>();
    /**
     * 表达式值
     */
    @Input() value: string;

    /**
     * 参数
     */
    @Input() editorParams: ExpressionEditorParam;

    /** 是否显示提示消息配置 */
    showMessageConfig = false;
    /** 是否显示提示消息类型配置 */
    showMessageTypeConfig = false;
    /** 提示消息枚举值 */
    messageTypes = [{ value: 'info', text: '提示' }, { value: 'warning', text: '警告' }, { value: 'error', text: '错误' }];

    /**
     * VO变量
     */
    contextEntities = [];
    /**
     * 系统变量
     */
    sessionEntities = [];

    /**
     * 表达式组件实体结构
     */
    // expSchema: ExpSchema;

    /**
     * 主实体编号
     */
    mainEntityCode = '';

    /**
     * 编辑器页尾组件
     */
    @ViewChild('bindingFooter') modalFooter: TemplateRef<any>;

    /**
     * 编辑器默认弹出窗口显示属性
     */
    get modalConfig() {
        return {
            title: this.editorParams.modalTitle || '表达式编辑器',
            width: 1060,
            height: 600,
            showButtons: true,
            buttons: this.modalFooter
        };

    }

    // @ViewChild(ExpressioneditorComponent) expEditor: ExpressioneditorComponent;

    @HostBinding('class')
    cls = 'w-100';

    constructor(
        private domServ: DomService,
        private notifyService: NotifyService,
        // private filterExprServ: FilterExprService,
        private formBasicService: FormBasicService) {
    }

    ngOnInit(): void {
        // this.contextEntities = this.filterExprServ.assembleContextEntities();
        // this.sessionEntities = this.filterExprServ.assembleSessionEntities();
        // this.expSchema = this.editorParams.hideFieldSchema ? [] : this.filterExprServ.assembleFieldSchema();

        // this.mainEntityCode = this.filterExprServ.mainEntityCode;


        // this.showMessageConfig = this.editorParams.hasOwnProperty('message');
        // this.showMessageTypeConfig = this.editorParams.hasOwnProperty('messageType');

        // if (this.showMessageTypeConfig && !this.editorParams.messageType) {
        //     this.editorParams.messageType = 'info';
        // }

    }

    /**
     * 点击确定
     */
    clickConfirm() {
        // const expr = this.expEditor.getExpr();
        // if (!expr) {
        //     this.notifyService.warning('请先配置表达式');
        //     return;
        // }
        // if (this.editorParams.expType !== 'defaultValue') {
        //     const expId = this.saveExpression(expr);
        //     this.submitModal.emit({ value: expr, parameters: expId, type: 'Expression' });
        // } else {
        //     this.submitModal.emit({ value: expr, parameters: expr, type: 'Expression' });
        // }

    }

    saveExpression(exprValue: string) {
        if (!this.domServ.expressions) {
            this.domServ.expressions = [];
        }
        const newExpConfig = new FormExpressionConfig();
        newExpConfig.id = this.editorParams.fieldId + '_' + this.editorParams.expType;
        newExpConfig.type = this.editorParams.expType;
        newExpConfig.value = exprValue;

        if (this.showMessageConfig) {
            newExpConfig.message = this.editorParams.message;
        }
        if (this.showMessageTypeConfig) {
            newExpConfig.messageType = this.editorParams.messageType;
        }

        const expField = this.domServ.expressions.find(e => e.fieldId === this.editorParams.fieldId);

        if (!expField) {
            if (this.formBasicService.envType === 'mobileDesigner'){
                const cmp = this.domServ.getComponentByVMId(this.editorParams.viewModelId);
                
                this.domServ.expressions.push(
                    {
                        fieldId: this.editorParams.fieldId,
                        viewModelId:cmp.id,
                        expression: [newExpConfig]
                    });
            }else{
                this.domServ.expressions.push(
                    {
                        fieldId: this.editorParams.fieldId,
                        expression: [newExpConfig]
                    });
            }

        } else {
            const originalExp = expField.expression.find(e => e.type === this.editorParams.expType);
            if (!originalExp) {
                expField.expression.push(newExpConfig);
            } else {
                Object.assign(originalExp, newExpConfig);
            }
        }

        return newExpConfig.id;

    }

    /**
     * 点击取消
     */
    clickCancel() {
        this.closeModal.emit();

    }

}


export class ExpressionEditorParam {

    /** 弹窗标题 */
    modalTitle?: string;

    // 字段ID
    fieldId: string;

    // 视图模型ID
    viewModelId: string;

    /**  表达式类型：readonly|require|compute|validate|dependency|dataPicking */
    expType: string;

    /** 提示消息 */
    message?: string;

    /** 提示消息类型 */
    messageType?: string;

    /** 是否隐藏实体字段 */
    hideFieldSchema?: boolean;

}
